package timbap.visualizer.impl.context.playlist;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.farng.mp3.MP3File;
import org.farng.mp3.id3.AbstractID3;
import timbap.visualizer.api.exceptions.PlaylistParserException;
import timbap.visualizer.api.model.PlaylistEntry;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

public class ID3ParsingM3UPlaylistManagerImpl extends M3UPlaylistManagerImpl {

    private static final Log LOG = LogFactory.getLog(ID3ParsingM3UPlaylistManagerImpl.class);
    
    @Override
    public List<PlaylistEntry> parsePlaylist(File pPlaylistFile)
            throws IOException, PlaylistParserException {
        
        List<PlaylistEntry> tPlaylist = new ArrayList<PlaylistEntry>();
        LineNumberReader tLineNumberReader = 
            new LineNumberReader(new FileReader(pPlaylistFile));
        
        String tCurrentLine;
        while ((tCurrentLine = tLineNumberReader.readLine()) != null) {
            PlaylistEntry tParsedPlaylistEntry = parsePlaylistItem(pPlaylistFile.getParentFile(), true, tCurrentLine);
            tPlaylist.add(tParsedPlaylistEntry);
        }
        tLineNumberReader.close();
        
        return tPlaylist;
    }


    protected PlaylistEntry parsePlaylistItem(File pReferenceDirectory, boolean pReadFromID3Tags, String... pLinesToParse) {

        PlaylistEntry tPlaylistEntry = null;

        if (pLinesToParse != null && pLinesToParse.length == 1) {
            String tAudioFilePath = pLinesToParse[0];
            tPlaylistEntry = super.parsePlaylistItem(pReferenceDirectory, tAudioFilePath);
        }
        
        if (pReadFromID3Tags) {
            fillMetaDataFromId3Tags(tPlaylistEntry);
        } 
        return tPlaylistEntry;
    }


    public void fillMetaDataFromId3Tags(PlaylistEntry pPlaylistEntry) {
    	
    	File tAudioFile = pPlaylistEntry.getAudioFile();
    	if (tAudioFile.canRead() && tAudioFile.length() > 0) {
	    	MP3File mp3File = null;
	    	try {
				mp3File = new MP3File(tAudioFile);
			} catch (Exception e) {
				LOG.warn("Error parsing mp3 data of mp3 file " 
						+ pPlaylistEntry.getAudioFile() + ": " + e.getMessage());
			} 
			AbstractID3 tID3TagInfo = null;
			if (mp3File != null) {
                /* reversed order because of ISO-8859-1 problems
                if (mp3File.hasID3v2Tag()) {
					LOG.info("Reading ID3v2 tags from " + tAudioFile);
					tID3TagInfo = mp3File.getID3v2Tag();
				} else if (mp3File.hasID3v1Tag()) {
					LOG.info("Reading ID3v1 tags from " + tAudioFile);
					tID3TagInfo = mp3File.getID3v1Tag();
				}
				*/
                if (mp3File.hasID3v1Tag()) {
					LOG.info("Reading ID3v1 tags from " + tAudioFile);
					tID3TagInfo = mp3File.getID3v1Tag();
				} else if (mp3File.hasID3v2Tag()) {
					LOG.info("Reading ID3v2 tags from " + tAudioFile);
					tID3TagInfo = mp3File.getID3v2Tag();
				}
            }
			if (tID3TagInfo != null) {
				String tArtistName = tID3TagInfo.getLeadArtist();
				String tSongTitle = tID3TagInfo.getSongTitle();
				String tAlbumTitle = tID3TagInfo.getAlbumTitle();
				String tSongGenre = tID3TagInfo.getSongGenre();
				String tYearReleased = tID3TagInfo.getYearReleased();
				if (tArtistName != null && tArtistName.length() > 0) {
					pPlaylistEntry.setArtistName(tArtistName);
				}
				if (tSongTitle != null && tSongTitle.length() > 0) {
					pPlaylistEntry.setSongTitle(tSongTitle);
				}
				if (tAlbumTitle != null && tAlbumTitle.length() > 0) {
					pPlaylistEntry.setAlbumTitle(tAlbumTitle);
				}
				if (tSongGenre != null && tSongGenre.length() > 0) {
					pPlaylistEntry.setSongGenre(tSongGenre);
				}
				if (tYearReleased != null && tYearReleased.length() > 0) {
					try {
						pPlaylistEntry.setYearReleased(Integer.parseInt(tYearReleased));
					} catch (NumberFormatException e) {
						LOG.warn("MP3 File " + tAudioFile + " has invalid release year tag");
					}
				}
			}
    	}
    }
    
}
